package com.cloudsubassemblykafka10024.idempotence;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @Description: Kafka 生产者快速入门
 * @Author zx
 * @Date 2024/12/24 19:55
 * @Version 1.0
 */
public class KafkaProducerIdempotence_001 {
    public static void main(String[] args) {

        // 创建 Kafka Producer
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.18.220:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        // 设置Kafka的Ack以及retries
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        properties.put(ProducerConfig.RETRIES_CONFIG, 3);
        // 将检测超时的时间设置为1ms
        properties.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 1);
        // 开启Kafka幂等性
        properties.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(properties);


        ProducerRecord<String, String> producerRecord = new ProducerRecord<>("messageDML004", "Test", "ACK测试");
        kafkaProducer.send(producerRecord);
        kafkaProducer.flush();

        // 关闭资源
        kafkaProducer.close();

    }
}
